﻿#include "QQChatIndexDelegate.h"

QQChatIndexDelegate::QQChatIndexDelegate(QObject* parent)
	: QStyledItemDelegate(parent)
{
}

QQChatIndexDelegate::~QQChatIndexDelegate()
{
}

void QQChatIndexDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
	QStyleOptionViewItem viewOption(option);
	this->initStyleOption(&viewOption, index);

	QRect itemRect = option.rect;

	painter->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);

	painter->save();
	itemRect.adjust(0, 2, 0, -2);
	QPainterPath path;
	path.addRoundedRect(itemRect, 4, 4);
	if (viewOption.state & QStyle::State_Selected)
	{
		if (viewOption.state & QStyle::State_MouseOver)
		{
			painter->fillPath(path, QColor("#0078D4"));
		}
		else
		{
			painter->fillPath(path, QColor("#0078D4"));
		}
	}
	else
	{
		if (viewOption.state & QStyle::State_MouseOver)
		{
			painter->fillPath(path, ElaThemeColor(ElaThemeType::Light, BasicHoverAlpha));
		}
	}
	painter->restore();


	painter->save();
	QPixmap icon = index.data(Qt::UserRole + 1).value<QPixmap>();
	icon = icon.scaled(mIconWidth, mIconWidth, Qt::KeepAspectRatio, Qt::SmoothTransformation);
	QRect iconRect = QRect(itemRect.x() + mSpace / 2, itemRect.y() + itemRect.height() / 2 - mIconWidth / 2, mIconWidth, mIconWidth);
	painter->drawPixmap(iconRect, icon);
	painter->restore();

	painter->save();
	if (option.state & QStyle::State_Selected)
	{
		painter->setPen(Qt::white);
	}
	else
	{
		painter->setPen(Qt::black);
	}
	QString name = index.data(Qt::UserRole + 2).toString();
	name = painter->fontMetrics().elidedText(name, Qt::ElideRight, mNameSize.width());
	QRect nameRect = QRect(itemRect.x() + mIconWidth + mSpace, iconRect.y(), mNameSize.width(), mNameSize.height());
	painter->drawText(nameRect, Qt::AlignLeft | Qt::TextWordWrap, name);
	painter->restore();

	int keyPoints = index.data(Qt::UserRole + 3).toInt();
	if (keyPoints)
	{
		painter->save();
		painter->setPen(Qt::NoPen);
		painter->setBrush(Qt::white);
		painter->drawEllipse(QPoint(itemRect.width() - 2 * mSpace, itemRect.y() + itemRect.height() / 2), 8, 8);
		painter->setBrush(ElaThemeColor(ElaThemeType::Light, StatusDanger));
		painter->drawEllipse(QPoint(itemRect.width() - 2 * mSpace, itemRect.y() + itemRect.height() / 2), 7, 7);
		painter->setPen(QPen(Qt::white, 2));
		QFont font = painter->font();
		font.setBold(true);
		if (keyPoints > 99)
		{
			keyPoints = 99;
		}
		if (keyPoints > 9)
		{
			font.setPixelSize(10);
		}
		else
		{
			font.setPixelSize(11);
		}
		painter->setFont(font);
		int textX = itemRect.width() - 2 * mSpace - painter->fontMetrics().horizontalAdvance(QString::number(keyPoints)) / 2;
		painter->drawText(textX, itemRect.y() + itemRect.height() / 2 + 4, QString::number(keyPoints));
		painter->restore();
	}
}